﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @ok="handleSubmit"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="客户名称" prop="CustomerName">
              <UserSample @closeMode="CustomerChange" v-model="entity.CustomerName" />
              <!-- <a-input v-model="entity.CustomerName" autocomplete="off" placeholder="客户名称" /> -->
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="收件人" prop="Addressee">
              <a-input v-model="entity.Addressee" autocomplete="off" placeholder="收件人" />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="联系电话" prop="AddresseeTel">
              <a-input v-model="entity.AddresseeTel" autocomplete="off" placeholder="联系电话" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="收件地址" prop="ExpressAddress">
              <a-input v-model="entity.ExpressAddress" autocomplete="off" placeholder="收件地址" />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="开票金额" prop="InvoicedAmount">
              <a-input
                style="text-align: right;"
                v-model="entity.InvoicedAmount"
                disabled
                autocomplete="off"
                placeholder="开票金额"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="开票内容" prop="QequestDescription">
              <a-input v-model="entity.QequestDescription" autocomplete="off" placeholder="开票内容" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="备注" prop="Remark">
              <a-input v-model="entity.Remark" autocomplete="off" placeholder="备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <OrderDetails @onOrder="onOrder" ref="OrderDetails" />
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp; <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
    <a-table
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => index"
      :dataSource="data"
      :pagination="false"
      :rowClassName="rowClassName"
      :loading="loading"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record, index">
        <template>
          <a @click="handleDelete(index)">删除</a>
        </template>
      </span>
    </a-table>
  </a-drawer>
</template>

<script>
const toThousands = function(data) {
  if (data != null) {
    return data.toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
  } else {
  }
}
import OrderDetails from '@/components/Order/OrderDetails.vue'
const columns = [
  { title: '订单编号', dataIndex: 'cSOCode' },
  { title: '销售类型', dataIndex: 'cSTName' },
  {
    title: '单据日期',
    dataIndex: 'dDate',
    align: 'center',
    customRender: (value, row) => {
      //console.log(row)

      return row.dDate.substring(0, 10)
    },
    width: '10%'
  },
  { title: '订单金额', dataIndex: 'OrderMoney', align: 'right', customRender: toThousands },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]
import UserSample from '@/components/Myuser/List.vue'

export default {
  components: {
    UserSample,
    OrderDetails
  },
  props: {
    parentObj: Object
  },
  watch: {
    data: {
      handler(n, o) {
        let a = 0
        if (n.length > 0) {
          n.forEach(item => {
            a += item.OrderMoney
          })
        }

        var c = a.toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
        this.$set(this.entity, 'InvoicedAmount', c)
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      data: [],
      columns,
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: {},
      rules: {
        CustomerName: [{ required: true, message: '未输入', trigger: 'blur' }],
        InvoicedAmount: [{ required: true, message: '未输入', trigger: 'blur' }],
        Addressee: [{ required: true, message: '未输入', trigger: 'blur' }],
        AddresseeTel: [{ required: true, message: '未输入', trigger: 'blur' }, { validator: this.checkPhone }],
        ExpressAddress: [{ required: true, message: '未输入', trigger: 'blur' }]
      },
      title: ''
    }
  },
  methods: {
    handleDelete(i) {
      this.data.splice(i, 1)
    },
    rowClassName(record, index) {
      if (record.cSOCode == '合计') {
        return 'heji'
      }
    },

    onOrder(a) {
      console.log(a)
      a.forEach(element => {
        this.data.push(element)
      })
    },
    addTable() {
      if (this.entity.CustomerId) {
        this.$refs.OrderDetails.openChoose(this.entity.CustomerId, this.data)
      } else {
        this.$message.warning('请先选择客户')
      }
    },
    close() {
      this.visible = false
    },
    checkPhone(rule, value, callback) {
      const pwdRegex = new RegExp('^(13[0-9]|14[5-9]|15[0-35-9]|16[25-7]|17[0-8]|18[0-9]|19[0135689])[0-9]{8}$')
      if (!pwdRegex.test(value)) {
        callback(new Error('电话号码输入格式有误'))
      }
      callback()
    },
    CustomerChange(row) {
      console.log(row)
      this.$set(this.entity, 'CustomerName', row.cCusName)
      this.$set(this.entity, 'CustomerId', row.cCusCode)
      this.$set(this.entity, 'ExpressAddress', row.cCusAddress)

      this.$http
        .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListByConditions', {
          Search: [
            {
              Condition: 'CustomerId',
              Keyword: row.cCusCode
            }
          ],
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.UserList = resJson.Data

          if (this.UserList.length > 0) {
            this.$set(this.entity, 'Addressee', this.UserList[0].Name)
            this.$set(this.entity, 'AddresseeTel', this.UserList[0].Tel_Code)
          }
        })
    },

    init() {
      this.visible = true
      this.entity = {}
      this.data = []
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    async openForm(id, title) {
      this.init()
      this.title = title
      if (id) {
        const resJson = await this.$http.post('/InvoicesManagement/INV_InvoiceApply/GetTheData', { id: id })
        this.entity = resJson.Data

        const res = await this.$http.post('/OrderManagement/SO_SOMain/GetDataListByInvoiceApplyId', {
          Search: {
            CustomerId: this.entity.CustomerId,
            InvoiceApplyId: id
          }
        })
        this.data = res.Data
      }
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        var entityData = { ...this.entity }
        let cSOCode = this.data.map(item => {
          return item.cSOCode
        })
        var CSOCode_List = [...cSOCode]

        //console.log(this.CSOCode_List)

        entityData.CSOCode_List = CSOCode_List
        this.$http.post('/InvoicesManagement/INV_InvoiceApply/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false

            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.heji {
  position: sticky;
  bottom: 0;
  background: #fff;
  font-size: 19px;
  font-weight: bold;
}
</style>
